package cn.turboinfo.fuyang.api.provider.framework.spring;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.beans.PropertyDescriptor;

/**
 * author: sunshow.
 */
@Slf4j
public class RedirectAttributesHelper {

    public static <PropertiesSource> void setAllFlashAttributes(RedirectAttributes redirectAttributes, PropertiesSource source) {
        PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(source.getClass());
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String fieldName = propertyDescriptor.getName();
            try {
                Object fieldValue = PropertyUtils.getProperty(source, fieldName);
                if (fieldValue != null) {
                    redirectAttributes.addFlashAttribute(fieldName, fieldValue);
                }
            } catch (IllegalAccessException | NoSuchMethodException e) {
                // did nothing
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                log.error("类属性拷贝错误, message={}, fieldName={}", e.getMessage(), fieldName);
            }
        }
    }

}
